/**
 * 汇算清缴/财务报表公共填写模块
 * 大连 广东 贵州 陕西 北京
 */

import { isFillYearBeforeLast, saasTosj, waitTimeOut } from "./common.js";
import DGGS from "./commonModule/DGGS.js";
import { hsqjInputJson, gdzczjJson } from './hsqj-json.js'
import { CWBB_JSON } from './cwbb-json.js'
import { transformCwbbDataXqykjzz, transformCwbbDataQykjzz } from "./DGGSB/xqykjzz/index.js"
import { fillInputDone } from "./message.js"
/**
 *
 * @param {*} data setSaasData事件的回调data
 * @param {*} baseInfoCache 账套基础数据
 */
async function hsqj_input_common_GSDGB(data, baseInfoCache) {
  let sheet = data.saasData.sheet;
  let sheetType = data.saasData.sheetType
  let isYearReport = data.saasData.isYearReport
  let type = data.baseInfo.taxInfo.institution
  if (sheet === "sds" || sheet === "zzs") {
    // todo...
  } else if (sheetType.includes('hsqj')) {
    const transformData = saasTosj(data, hsqjInputJson, gdzczjJson);
    await fillInputHsqj(transformData, sheet, data.saasData);
  } else if (sheetType === 'cwbb' && isYearReport) {
    const transformData = transformCwbbData(sheet, type, data.saasData, baseInfoCache)
    await fillInputHsqj(transformData, sheet, data.saasData);
  } else if (sheetType === 'cwbb' && [440000, 110000, 610000, 520000].includes(baseInfoCache.companyInfo.provId)) { // 广东关东财务报表月季报
    if (type === '2013') {
      const transformData = transformCwbbDataXqykjzz(sheet, type, data.saasData, baseInfoCache)
      await fillInputHsqj(transformData, sheet, data.saasData);
    } else {
      const transformData = transformCwbbDataQykjzz(sheet, type, data.saasData, baseInfoCache)
      await fillInputHsqj(transformData, sheet, data.saasData);
    }
  }
}


/**
 * 转换财务报表数据
 * @param {*} sheet 表类型-资产负债表、利润表、现金流量表
 * @param {*} type 会计准则类型
 * @param {*} saasData 系统数据
 * @param {*} baseInfoCache 账套数据
 */
function transformCwbbData(sheet, type, saasData, baseInfoCache) {
  // 根据表类型和会计准则类型确定转换json
  const transformJson = CWBB_JSON[sheet][type]
  let inputData = {}
  if (sheet === 'balance') {
    inputData = transformBalance(saasData, transformJson)
  } else if (sheet === 'profit') {
    inputData = transformProfit(saasData, transformJson, baseInfoCache)
  } else if (sheet === 'cash') {
    inputData = transformCash(saasData, transformJson, baseInfoCache)
  }
  return inputData
}

function transformCash(saasData, transformJson, baseInfoCache) {
  const nowCash = saasData.data.openParams.inputData.data.cash
  const lastCash = saasData.data.openParams.inputData.lastYearData.cash
  const transformJsonNowCash = transformJson.now
  const transformJsonLastCash = transformJson.last
  let result = {}
  for (let key in transformJsonNowCash) {
    const item = nowCash.filter(item => item.reportItemUuid === transformJsonNowCash[key]['uuid'])
    if (item.length) {
      result[key] = item[0][transformJsonNowCash[key]['value']] ? Number(item[0][transformJsonNowCash[key]['value']]) : 0
    }
  }
  if (isFillYearBeforeLast(baseInfoCache)) {
    for (let key in transformJsonLastCash) {
      const item = lastCash.filter(item => item.reportItemUuid === transformJsonLastCash[key]['uuid'])
      if (item.length) {
        result[key] = item[0][transformJsonLastCash[key]['value']] ? Number(item[0][transformJsonLastCash[key]['value']]) : 0
      }
    }
  }
  return result
}

function transformProfit(saasData, transformJson, baseInfoCache) {
  const nowProfit = saasData.data.openParams.inputData.data.profit
  const lastProfit = saasData.data.openParams.inputData.lastYearData.profit
  const transformJsonNowProfit = transformJson.now
  const transformJsonLastProfit = transformJson.last
  let result = {}
  for (let key in transformJsonNowProfit) {
    const item = nowProfit.filter(item => item.reportItemUuid === transformJsonNowProfit[key]['uuid'])
    if (item.length) {
      result[key] = item[0][transformJsonNowProfit[key]['value']] ? Number(item[0][transformJsonNowProfit[key]['value']]) : 0
    }
  }
  if (isFillYearBeforeLast(baseInfoCache)) {
    for (let key in transformJsonLastProfit) {
      const item = lastProfit.filter(item => item.reportItemUuid === transformJsonLastProfit[key]['uuid'])
      if (item.length) {
        result[key] = item[0][transformJsonLastProfit[key]['value']] ? Number(item[0][transformJsonLastProfit[key]['value']]) : 0
      }
    }
  }
  return result
}

function transformBalance(saasData, transformJson) {
  const { balance } = saasData.data.openParams.inputData.data
  let result = {}
  for (let key in transformJson) {
    const item = balance.filter(item => item.reportItemUuid === transformJson[key]['uuid'])
    if (item.length) {
      result[key] = item[0][transformJson[key]['value']] ? Number(item[0][transformJson[key]['value']]) : 0
    }
  }
  return result
}

async function fillInputHsqj(inputData, sheet, saasData) {
  let iframeWindow = window.frames.frmMain.frames.frmSheet; // 填报iframe Window对象 财务报表与汇算清缴一致
  let message = "填报成功 ";
  try {
    message = await angularFill(
      inputData,
      iframeWindow,
      message,
      sheet,
      saasData
    );
  } catch (e) {
    message = "填报失败" + e;
  }

  fillInputDone({
    message: message,
  })
}

/**
 * 按照angular方式填充
 * @param inputData 原始数据
 * @param iframeWindow 填报iframe的window
 * @param message 提示信息
 * @param sheet 报表类型
 * @param {lastYearData, isYearReport} // 上年数据 是否为年报
 */
async function angularFill(
  inputData,
  iframeWindow,
  message,
  sheet,
  { lastYearData, isYearReport }
) {
  let angular = iframeWindow.angular;
  let controllerScope = angular.element("#viewCtrlId").scope();

  // if (isYearReport) {
  //   inputData = DGGS.hackYearReportInput(inputData, lastYearData, sheet);
  // }

  for (let key in inputData) {
    let value = Number.parseFloat(inputData[key]).toFixed(2) || "0.00";
    let keyFormObj = key.split(".")[0].split('[')[0];
    let formVal = eval("controllerScope." + keyFormObj);
    let tdVal = formVal ? eval("controllerScope." + key) : "undefined";
    const input = iframeWindow.document.querySelector(`input[ng-model="${key}"]`)
    if (tdVal !== "undefined") {
      if (input && !input.readOnly) {
        eval("controllerScope." + key + "=" + value);
      }
    }
  }

  angular.element("#viewCtrlId").scope().$apply();

  DGGS.tiggerDomByInputDataKey(inputData, sheet, isYearReport, iframeWindow);

  // 保证触发税局计算完成
  await waitTimeOut(1000);

  return message;
}

export { hsqj_input_common_GSDGB };
